<?php
/*
 *   class.browser.php - Browser Class for Indexer
 *   Copyright 2011 Saravana Kumar.A <saravanakumar.a.o@gmail.com>
 *      
 */

class Browser
{
  public $Exceptions;
  public $Root_dir;
    
  // Iconset
  public $Icons = array(
                  'exe'=>array('Executable File', 'binary.gif'), 'pdf'=>array('PDF Document', 'pdf.gif'),
                  'zip'=>array('Zip File', 'compressed.gif'), '7z'=>array('7Zip File', 'compressed.gif'),
                  'mp3'=>array('MP3 Audio', 'sound.gif'), 'mp4'=>array('MP4 Video', 'video.gif'),
                  '3gp'=>array('3GP Video', 'video.gif'), 'htm'=>array('Web Document', 'html.gif'),
                  'html'=>array('Web Document', 'html.gif'), 'php'=>array('PHP Script', 'script.gif'),
                  'js'=>array('Java Script', 'script.gif'), 'txt'=>array('Text Document', 'text.gif'),
                  'jpeg'=>array('JPEG Image', 'image.gif'), 'jpg'=>array('JPG Image', 'image.gif'),
                  'png'=>array('PNG Image', 'image.gif'), 'gif'=>array('GIF Image', 'image.gif')
                  );
  
  public function Browse($dir) {
    $dir_t    = ($dir == '/')? '': $dir;
    $dir_path   = $this->Root_dir.$dir_t;
    $dirp       = ($dir == '')? '/': $dir;
    
    $folderdata = $this->getDirectorySize($this->Root_dir);
    $_SESSION['usage'] = $folderdata['size'];
    $usage = $this->convertFileSize($folderdata['size']);
    
    if($filesarr = @scandir($dir_path)) $files      = $this->CleanupFiles($filesarr);
    else die("[ $dir_path ] is not readable!");
      
    $parent     = $this->GetParentDir($dir);
    $parenthref = "javascript: Browse('".htmlspecialchars($parent, ENT_QUOTES)."');";
    $icons      = $this->Icons;
    
    $Indexer_Web_Dir  =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'],"/")) . "/";
    
    // Generate links
    $links = array();
        
    $c = 0;
    foreach($files as $file) {
      
      // If entry is a file...
      if(is_file("$dir_path/$file")) {
        $links[$c]['name'] = "<font class=\"files\">$file</font>";
        $links[$c]['href'] = "javascript: Download('".htmlspecialchars($dirp, ENT_QUOTES)."', '".htmlspecialchars($file, ENT_QUOTES)."');";
        $links[$c]['file'] = "$dir_t/$file";
        $links[$c]['size'] = $this->convertFileSize(filesize("$dir_path/$file"));
        // Get file type & icons
        $fext = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($fext, $icons)) {
          $links[$c]['type'] = $icons[$fext][0];
          $links[$c]['icon'] = "images/iconset/{$icons[$fext][1]}";
        }  else {
          $links[$c]['type'] = 'Unknown File';
          $links[$c]['icon'] = 'images/iconset/unknown.gif';
        }
      }
      
      // If entry is a folder...
      elseif(is_dir("$dir_path/$file")) {
        $links[$c]['name'] = "<font class=\"folders\">$file</font>";
        $links[$c]['icon'] = 'images/iconset/folder.gif';
        $links[$c]['href'] = "javascript: Browse('".htmlspecialchars("$dir_t/$file", ENT_QUOTES)."');";
        $links[$c]['file'] = "$dir_t/$file";
        $links[$c]['type'] = 'Directory';
        $folderdata = $this->getDirectorySize("$dir_path/$file");
        $links[$c]['size'] = $this->convertFileSize($folderdata['size']);
      }
      
      $c=$c+1;
    }
        
    ksort($links);
    echo <<<PARENT
      <div class="row" id="parent">
      <input type="hidden" id="getusage" value="$usage" name="usage" />
      <input type="hidden" id="getusagebytes" value="{$_SESSION['usage']}" name="usagebytes" />
        <a style="text-decoration: none;" href="$parenthref">
          <span class="iconcolumn">
            <img class="iconimage" src="images/iconset/up.gif" alt="ico" />
          </span>
          <span class="namecolumn">
            Parent Folder
          </span>
          <span class="typecolumn">
            &nbsp;
          </span>
          <span class="sizecolumn">
            &nbsp;
          </span>
        </a>
      </div>
PARENT;
   echo <<<SHARE
      <div class="row" id="share">
        <a style="text-decoration: none;" href="javascript: gotoSharedFolder();">
          <span class="iconcolumn">
            <img class="iconimage" src="images/iconset/folder.png" alt="ico" />
          </span>
          <span class="namecolumn">
            My Shared Folder
          </span>
          <span class="typecolumn" id="shareditems_count">
            No Shared Files Found!
          </span>
          <span class="sizecolumn">
            &nbsp;
          </span>
        </a>
      </div>
SHARE;

    if(count($links) < 1)
    die("&nbsp;No Files Found! Empty Directory!");
    
    foreach($links as $link)
    echo <<<RESPONSE
      <div class="row">
        <span class="iconcolumn">
          <img class="iconimage" src="{$link['icon']}" alt="ico" />
        </span>
        <span class="namecolumn">
          <a href="{$link['href']}">{$link['name']}</a>
        </span>
        <span class="typecolumn">
          {$link['type']}
        </span>
        <span class="sizecolumn">
          {$link['size']}
        </span>
        <span class="checkboxcolumn">
          <input type="checkbox" name="files[]" value="{$link['file']}" />
        </span>
      </div>
RESPONSE;
    
    exit;
    
  }
  
  private function CleanupFiles($files_array) {
    foreach($files_array as $k => $f) {
      foreach($this->Exceptions as $e)      
      if(strcasecmp($e, $f) == 0) unset($files_array[$k]);
    }
    return $files_array;
  }
  
  private function GetParentDir($dir) {
    //Remove Trialing Slashes & Proceed
    if( substr($dir, -1) == "/" ) $dir = substr($dir, 0, strlen($dir) - 1);
    $parent = substr($dir, 0, strrpos($dir, '/'));
    return (empty($parent))? '/': $parent;
  }
  
  private function getDirectorySize($path) {
    $totalsize = 0;
    $totalcount = 0;
    $dircount = 0;
    if($handle = opendir ($path)) {
      while (false !== ($file = readdir($handle))) {
        $nextpath = $path . '/' . $file;
        if($file != '.' && $file != '..' && !is_link ($nextpath)) {
          if(is_dir ($nextpath)) {
            $dircount++;
            $result = $this->getDirectorySize($nextpath);
            $totalsize += $result['size'];
            $totalcount += $result['count'];
            $dircount += $result['dircount'];
          }
          elseif(is_file ($nextpath)) {
            $totalsize += filesize ($nextpath);
            $totalcount++;
          }
        }
      }
    }
    closedir ($handle);
    $total['size'] = $totalsize;
    $total['count'] = $totalcount;
    $total['dircount'] = $dircount;
    return $total;
  }

  private function convertFileSize($size) {
    if($size<1024) {
      return $size." B";
    } 
    else if($size<(1024*1024)) {
      $size=round($size/1024,1);
      return $size." KB";
    }
    else if($size<(1024*1024*1024)) {
      $size=round($size/(1024*1024),1);
      return $size." MB";
    }
    else {
      $size=round($size/(1024*1024*1024),1);
      return $size." GB";
    }
  }  
}

//Execution
require_once('../../conf/main.conf.php');
$dir = $_GET['dir'];
$browser = new Browser();
$browser->Root_dir = $Root_dir;
$browser->Exceptions = $Exceptions;
$browser->Browse($dir);
?>
